package com.cindata

import com.cindata.dictionary.*
import grails.converters.JSON
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Transactional
@Secured(['isAuthenticated()'])
class ValuationHistoryController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService
    def apiService
    def splitMatchApiService

    def index(Integer max)
    {
        def user = User.findById(springSecurityService.principal.id)
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        max = params.max
        def sort = params['sort']
        def order = params['order']
        def name = params['name']
        def type = params['type']
        def offset = params.offset
        def sql = " from ValuationHistory m where 1=1 and m.user.id = ${user.id}"
        if (name)
        {
            sql += " and m.name like '%${name}%'"
        }
        if (type) 
        {
            sql += " and m.sourceClass = '${type}'"
        }
        def sql1 = " select count(*) " + sql
        if (order && sort)
        {
            sql += " order by m.${sort} ${order}"
        }
        else
        {
            sql += " order by m.createdDate desc"
        }

        def list = ValuationHistory.executeQuery(sql, [max: max, offset: offset]).asList()
        def count = ValuationHistory.executeQuery(sql1)
        respond list, model: [valuationHistoryCount: count[0]]
    }

    def show(ValuationHistory valuationHistory)
    {
        respond valuationHistory
    }

    def create()
    {
        respond new ValuationHistory(params)
    }

    @Transactional
    def save(ValuationHistory valuationHistory)
    {
        if (valuationHistory == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (valuationHistory.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond valuationHistory.errors, view: 'create'
            return
        }

        valuationHistory.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'valuationHistory.label', default: 'ValuationHistory'), valuationHistory.id])
                redirect valuationHistory
            }
            '*' { respond valuationHistory, [status: CREATED] }
        }
    }

    def edit(ValuationHistory valuationHistory)
    {
        respond valuationHistory
    }

    @Transactional
    def update(ValuationHistory valuationHistory)
    {
        if (valuationHistory == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (valuationHistory.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond valuationHistory.errors, view: 'edit'
            return
        }

        valuationHistory.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'valuationHistory.label', default: 'ValuationHistory'), valuationHistory.id])
                redirect valuationHistory
            }
            '*' { respond valuationHistory, [status: OK] }
        }
    }

    @Transactional
    def delete(ValuationHistory valuationHistory)
    {

        if (valuationHistory == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        valuationHistory.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'valuationHistory.label', default: 'ValuationHistory'), valuationHistory.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'valuationHistory.label', default: 'ValuationHistory'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    @Transactional
    def evaluate()
    {
        def user = User.findById(springSecurityService.principal.id)
        def status = ""
        def ids = params["ids"]
        def sourceClass = params.sourceClass
        try
        {
            def idList = new ArrayList()
            if (ids)
            {
                idList = ids.split(",")
            }
            idList?.each {
                def collateral = Collateral.findById(Long.parseLong(it))
                def sourceObject = collateral[sourceClass]
                sourceObject.latestEvaluatePrice = getRandomValue(sourceObject.firstEvaluatePrice)
                sourceObject.latestEvaluateDate = new Date()
                if (sourceObject.validate())
                {
                    sourceObject.save flush: true
                }
                else
                {
                    println sourceObject.errors
                }

                collateral.latestEvaluatePrice = sourceObject.latestEvaluatePrice
                collateral.latestEvaluateDate = new Date()
                if (collateral.validate())
                {
                    collateral.save flush: true
                }
                else
                {
                    println collateral.errors
                }

                // 生成评估记录
                ValuationHistory valuationHistory = new ValuationHistory()
                valuationHistory.name = collateral?.name
                valuationHistory.valuationDate = new Date()
                valuationHistory.totalPrice = sourceObject?.latestEvaluatePrice
                valuationHistory.sourceId = collateral?.id
                valuationHistory.sourceClass = sourceClass
                valuationHistory.evaluateStatus = ExecStatusDict.SUCCESS()
                valuationHistory.evaluateType = EvaluateDict.AUTOMATIC()
                valuationHistory.user = user

                if (valuationHistory.validate())
                {
                    valuationHistory.save()
                }
                else
                {
                    println valuationHistory.errors
                }
            }
            status = "success"
        }
        catch (Exception e)
        {
            e.printStackTrace()
            status = "false"
        }
        render([status: status] as JSON)
    }

    @Transactional
    def estateEvaluate()
    {
        def user = User.findById(springSecurityService.principal.id)
        def status = ""
        def ids = params["ids"]
        def sourceClass = params.sourceClass
        try
        {
            def idList = new ArrayList()
            if (ids)
            {
                idList = ids.split(",")
            }
            idList?.each 
            {
                def collateral = Collateral.findById(Long.parseLong(it))
                def sourceObject = collateral[sourceClass]

                // 拆分匹配
                def addressSplitList = splitMatchApiService.splitMatch(sourceObject?.city?.name, sourceObject?.sourceAddress)
                def communityId = addressSplitList?.match_community_id
                if (communityId && communityId != "-1")
                {
                    sourceObject.communityId = addressSplitList?.match_community_id?.toInteger()
                    sourceObject.communityName = addressSplitList?.match_community_name
                    sourceObject.buildingId = addressSplitList?.match_building_id?.toInteger()
                    sourceObject.buildingName = addressSplitList?.match_building_name
                    sourceObject.unitId = addressSplitList?.match_unit_id?.toInteger()
                    sourceObject.unitName = addressSplitList?.match_unit_name
                    sourceObject.houseId = addressSplitList?.match_house_id?.toInteger()
                    sourceObject.houseName = addressSplitList?.match_house_name
                    sourceObject.streetId = addressSplitList?.match_street_id?.toInteger()
                    sourceObject.streetName = addressSplitList?.match_street_name
                }

                // 评估
                def param = [em: 1,
                    city: sourceObject?.city?.name,
                    name: sourceObject?.communityName,
                    address: sourceObject?.sourceAddress,
                    floor: sourceObject?.sourceCurrentFloor,
                    totalfloor: sourceObject?.sourceTotalFloor,
                    square: sourceObject?.buildArea,
                    buildingName: sourceObject?.buildingName,
                    unitName: sourceObject?.unitName,
                    houseNumber: sourceObject?.houseName,
                    buildingYear: sourceObject?.buildYear]

                def result = apiService.assess(param)
                if (result.code == "0")
                {
                    sourceObject.unitPrice = result?.unitprice
                    sourceObject.latestEvaluatePrice = result?.saleprice
                    sourceObject.firstEvaluatePrice = sourceObject.firstEvaluatePrice ? sourceObject.firstEvaluatePrice : result?.saleprice
                    sourceObject.latestEvaluateDate = new Date()
                }
                // else
                // {
                //     println "评估失败，随机赋值！"
                //     sourceObject.latestEvaluatePrice = getRandomValue(sourceObject.firstEvaluatePrice)
                // }
                if (sourceObject.validate())
                {
                    sourceObject.save flush: true
                }
                else
                {
                    println sourceObject.errors
                }

                collateral.unitPrice = sourceObject.unitPrice
                collateral.latestEvaluatePrice = sourceObject.latestEvaluatePrice
                collateral.firstEvaluatePrice = sourceObject.firstEvaluatePrice
                collateral.latestEvaluateDate = sourceObject.latestEvaluateDate
                if (collateral.validate())
                {
                    collateral.save flush: true
                }
                else
                {
                    println collateral.errors
                }

                // 生成评估记录
                ValuationHistory valuationHistory = new ValuationHistory()
                valuationHistory.name = collateral?.name
                valuationHistory.valuationDate = new Date()
                valuationHistory.unitPrice = sourceObject?.unitPrice
                valuationHistory.totalPrice = sourceObject?.latestEvaluatePrice
                valuationHistory.sourceId = collateral?.id
                valuationHistory.sourceClass = sourceClass
                valuationHistory.evaluateStatus = ExecStatusDict.SUCCESS()
                valuationHistory.evaluateType = EvaluateDict.AUTOMATIC()
                valuationHistory.user = user

                if (valuationHistory.validate())
                {
                    valuationHistory.save flush: true
                }
                else
                {
                    println valuationHistory.errors
                }
            }
            status = "success"
        }
        catch (Exception e)
        {
            e.printStackTrace()
            status = "false"
        }

        def targetUri = request.getHeader("referer")
        render([status: status, targetUri: targetUri] as JSON)
    }

    def getRandomValue(Double val)
    {
        Double rvalue
        Random random = new Random()
        if (!val)
        {
            return random.nextInt(100000)
        }
        int iv = random.nextInt(10)
        boolean isadd = random.nextBoolean()
        if (isadd)
        {
            rvalue = val + val / 100 * iv
        }
        else
        {
            rvalue = val - val / 100 * iv
        }
        return rvalue
    }
}
